package com.cqkjxy.commons.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;

public final class IOHelper {

    private static final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };

    public static String replaceFileSeparatorWithSystem(String path) {
        if (StringUtils.isBlank(path)) {
            return "";
        }

        path = path.replace("\\", File.separator);
        path = path.replace("/", File.separator);
        return path;
    }

    public static String removeLastFileSeparator(String path) {
        if (path == null)
            return "";

        if (path.endsWith("/") || path.endsWith("\\"))
            return path.substring(0, path.length() - 1);

        return path;
    }

    public static String urlConcat(String path, String subPath) {
        return removeLastFileSeparator(path) + "/" + subPath;
    }

    public static String concat(String path, String subPath) {
        return removeLastFileSeparator(path) + File.separator + subPath;
    }

    public static String concat(String path, int subPath) {
        return removeLastFileSeparator(path) + File.separator + subPath;
    }

    public static void delete(String path) throws IOException {
        Files.deleteIfExists(Paths.get(path));
    }

    public static String formatFileSize(long fileSize) {
        if(fileSize <= 0) {
            return "0";
        }

        int digitGroups = (int) (Math.log10(fileSize) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(fileSize / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}
